<?php

namespace App\Http\Controllers\api;

use App\Models\Adreward;
use App\Models\Commission;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserWallet;
use App\Services\Wallet\UserWalletService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class UserController extends BaseController
{
    public function inviteCode()
    {
        /** @var User $user */
        $user = auth('jwt')->user();

        return $this->success([
            'share_link' => url(sprintf('invites?code=%s', $user->getAttribute('uuid')))
        ]);
    }

    public function groupCode()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        if (!$user->is_group_leader) {
            return $this->success([
                'share_link' => url(sprintf('invites?code=%s', $user->getAttribute('uuid')))
            ]);
        }

        return $this->success([
            'share_link' => url(sprintf('invites?code=%s&group=1', $user->getAttribute('uuid')))
        ]);
    }

    public function earnings(Request $request)
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $exchangeRate = Setting::get('exchange_rate');

        // 已邀请人数
        $invites = $user->children()->count();
        // 已赚金额
        $earnings = Commission::query()->where('user_id', $user->getAttribute('id'))->sum('user_money');
        // 可提现金额
        $withdrawable = sprintf('%.2f', UserWalletService::getWithdrawableCoins($user) / $exchangeRate);

        return $this->success([
            'invites' => $invites,
            'earnings' => sprintf('%.2f', $earnings),
            'withdrawable' => $withdrawable
        ]);
    }

    public function team(Request $request)
    {

        $user = auth('jwt')->user();

        $parent = $user->parent()->first();
        $user->parent_uuid = $parent->uuid ?? '';
        $user->is_group = $user->is_group_leader;
        //   $user->fans = User::where('parent_id', $user->id)->count();//粉丝
        // 今日新增粉丝
        $todayStart = \Carbon\Carbon::today();
        $todayEnd = Carbon::tomorrow();

// 昨日新增粉丝
        $yesterdayStart = Carbon::yesterday();
        $yesterdayEnd = Carbon::today();

        //是否是高级团长//is_advanced_group
        $one = 0;
        $two = 0;
        $three = 0;
        $ids = [];
        $twoids = [];
        if ($user->is_advanced_group) {

            $ids = User::where('parent_id', $user->id)->pluck('id')->toArray();
            if (!empty($ids)) {
                $one = count($ids);
                $twoids = User::whereIn('parent_id', $ids)->pluck('id')->toArray();
                if (!empty($twoids)) {
                    $two = count($twoids);
                    $three = User::whereIn('parent_id', $twoids)->count();
                }
            }
            $user->fans = $one + $two + $three;
            $user->one_fans = $one;
            $user->two_fans = $two;
            $user->three_fans = $three;

        } else {

            $ids = User::where('parent_id', $user->id)->pluck('id')->toArray();
            if (!empty($ids)) {
                $one = count($ids);
                $two = User::whereIn('parent_id', $ids)->count();
                $twoids = User::whereIn('parent_id', $ids)->pluck('id')->toArray();
            }
            $user->fans = $one + $two;
            $user->one_fans = $one;
            $user->two_fans = $two;
            $user->three_fans = $three;
        }
        $level = 3;
        if ($level == 1) {
            $list = User::where('parent_id', $user->id)->select('id', 'parent_id', 'uuid', 'username', 'avatar')->get();
            foreach ($list as &$item) {
                $item->withdrasum = UserWalletService::getUserWithdrawsum($item);
            }
            $user->teamlist = $list->toArray();
        } elseif ($level == 2) {
            $list = User::whereIn('parent_id', $ids)->select('id', 'parent_id', 'uuid', 'username', 'avatar')->get();
            foreach ($list as &$item) {
                $item->withdrasum = UserWalletService::getUserWithdrawsum($item);
            }
            $user->teamlist = $list->toArray();
        } elseif ($level == 3) {
            $list = User::whereIn('parent_id', $twoids)->select('id', 'parent_id', 'uuid', 'username', 'avatar')->get();
            foreach ($list as &$item) {
                $item->withdrasum = UserWalletService::getUserWithdrawsum($item);
            }
            $user->teamlist = $list->toArray();
        }
        return $this->success($user);
    }

    public function income(Request $request)
    {

        $user = auth('jwt')->user();
        $exchangeRate = Setting::get('exchange_rate');
        //红包收益
        $user->ad = Adreward::query()->where('user_id', $user->id)->sum('amount') / $exchangeRate;//个人收益
        //团队收益+//师徒收益+//任务xzb_task，xianwan_task，qianliang_task，duomi_task，shangbanwan_task，qie_task
        $user->team = Commission::query()->whereIn('source', ['group_cash'])->sum('amount') / $exchangeRate;
        $user->promotion = Commission::query()->whereIn('source', ['direct_invite'])->sum('amount') / $exchangeRate;
        $user->sumincome =round( $user->ad + $user->promotion + $user->team,2);
        $dateRange = collect(range(0, 14))
            ->map(fn($daysAgo) => \Illuminate\Support\Carbon::now()->subDays($daysAgo)->format('Y-m-d'));
        //红包收益
        $ad = Adreward::where('user_id', $user->id)->where('created_at', '>=', Carbon::now()->subDays(15)->startOfDay())
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('SUM(amount) as count'))
            ->groupBy('date')
            ->pluck('count', 'date');

        //团队收益
        $team = Commission::where('user_id', $user->id)->where('created_at', '>=', Carbon::now()->subDays(15)->startOfDay())
            ->whereIn('source', ['group_cash'])
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('SUM(amount) as count'))
            ->groupBy('date')
            ->pluck('count', 'date');
        //师徒收益
        $promotion = Commission::where('user_id', $user->id)->where('created_at', '>=', Carbon::now()->subDays(15)->startOfDay())
            ->whereIn('source', ['direct_invite'])
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('SUM(amount) as count'))
            ->groupBy('date')
            ->pluck('count', 'date');


// 合并日期范围与统计结果
        $user->dayincome = $dateRange->map(function ($date) use ($ad, $team, $promotion, $exchangeRate) {
            return [
                'date' => $date,
                'ad' => ($ad[$date] ?? 0) / $exchangeRate,
                'team' => ($team[$date] ?? 0) / $exchangeRate,
                'promotion' => ($promotion[$date] ?? 0) / $exchangeRate,
                'sumincome' => (($promotion[$date] ?? 0) + ($team[$date] ?? 0) + ($ad[$date] ?? 0)) / $exchangeRate,
            ];


        });
        return $this->success($user);
    }
    public function Upload(Request $request)
    {
        // 上传并获取路径
        $file = $request->file('avatar');
        $extension = $file->getClientOriginalExtension();
        $filename = uniqid() . '.' . $extension;
// 直接保存到public目录
        $file->move(public_path('avatars'), $filename);
// 生成URL
        $url = asset('avatars/' . $filename);
        return $this->success($url);
    }
}
